package com.fastdfs.util;

import com.fastdfs.exception.FileException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * Description
 * Author wangxh
 * Date 2020/7/17-4:00 下午
 * Version V1.0
 **/

@Component
public class FastDFSUtil {

    private static final Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    @Autowired
    StorageClient storageClient;

    public String uploadFile(MultipartFile fastFile){
        String originalFilename = fastFile.getOriginalFilename();
        logger.info("上传文件 --- {}" , originalFilename);
        if(StringUtils.isEmpty(originalFilename)){
            throw new FileException("上传文件不能为空");
        }
        try {
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            logger.info("扩展名: {}" , extName);
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", originalFilename);
            String[] result = storageClient.upload_file(fastFile.getBytes(), extName, metaList);
            String fileName = result[0] + "/" + result[1];
            logger.info("上传文件结果名: {}", fileName);
            return fileName;
        } catch (Exception e) {
            logger.error("上传文件 --- {}" , originalFilename,e );
            throw new FileException("上传文件失败");
        }
    }

}
